package com.quanyan.stadium.service.commonComponent.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.common.utils.HttpUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.messagepush.entity.*;
import com.quanyan.messagepush.enums.*;
import com.quanyan.stadium.service.commonComponent.MessagePushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Zheng.Ke
 * Date 2016/7/11.
 */
@Service
public class MessagePushServiceImpl implements MessagePushService {
    private static Logger logger = LoggerFactory.getLogger(MessagePushServiceImpl.class);

    @Value("${message.push.service.url}")
    private String messagePushServiceUrl;

    @Override
    public boolean pushReceiveInviteMessage(String title, int uid, String nickname, int datesportId, String imgUrl) {
        String boxTitle = String.format("“%s”邀请您参加约运动“%s”。", nickname, title);
        String lockTitle = "约运动消息：" + boxTitle;

        Jump jump = new Jump();
        jump.setIdType(IdType.DATESPORT_DETAIL_PAGE.value());
        jump.putToMap("datesportId", datesportId);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setJump(jump);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uid, lockTitle, boxTitle, payload);
    }

    @Override
    public boolean pushCreateDatesportSucessMsg(String title, int uid, int datesportId, String imgUrl) {
        String boxTitle = String.format("约运动“%s”创建成功。", title);
        String lockTitle = "约运动消息：" + boxTitle;

        Jump jump = new Jump();
        jump.setIdType(IdType.DATESPORT_DETAIL_PAGE.value());
        jump.putToMap("datesportId", datesportId);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setJump(jump);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uid, lockTitle, boxTitle, payload);
    }

    @Override
    public boolean pushUserAgreeMessage(String title, int uid, String nickname, int jumpUid, boolean isCreatorInvite, String imgUrl) {
        String boxTitle;
        if (isCreatorInvite) {
            boxTitle = String.format("“%s”已接受您的邀请并加入您创建的约运动“%s”。", nickname, title);
        } else {
            boxTitle = String.format("“%s”已加入您创建的约运动“%s”。", nickname, title);
        }

        String lockTitle = "约运动消息：" + boxTitle;

        Jump jump = new Jump();
        jump.setIdType(IdType.USER_HOME_PAGE.value());
        jump.putToMap("original", 2);//他人主页
        jump.putToMap("uid", jumpUid);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setJump(jump);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uid, lockTitle, boxTitle, payload);
    }

    @Override
    public boolean pushCreatorAgreeMessage(String title, int uid, int datesportId, String groupId, String imgUrl) {
        String boxTitle = String.format("恭喜，您已被同意加入约运动“%s”，快去和大家打招呼吧。", title);
        String lockTitle = "约运动消息：" + boxTitle;

        // 跳转
        Jump jump = new Jump();
        jump.setIdType(IdType.DATESPORT_DETAIL_PAGE.value());
        jump.putToMap("datesportId", datesportId);

        // 操作
        Operation operation = new Operation();
        operation.setIdType(IdType.DATESPORT_CHAT.value());
        operation.putToMap("groupId", groupId);
        operation.putToMap("nick", title);
        if (StringUtil.isBlankOrNull(imgUrl)) {
            imgUrl = "avatar";
        }
        operation.putToMap("avatar", imgUrl);
        operation.putToMap("uid", datesportId + "");

        List<Option> options = new ArrayList<Option>();
        Option option = new Option();
        option.setType(OperationType.CHAT.value());
        option.setText("开始聊天");
        options.add(option);

        operation.setOption(options);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.OPERATION_MSG.value());
        payload.setOperation(operation);
        payload.setJump(jump);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uid, lockTitle, boxTitle, payload);
    }

    @Override
    public boolean pushApplyForMessage(String title, int uid, String nickname, int jumpUid, int datesportId, String imgUrl) {
        String boxTitle = String.format("申请加入您创建的约运动“%s”。", title);
        String lockTitle = "约运动消息：“" + nickname + "”" + boxTitle;

        // 跳转
        Jump jump = new Jump();
        jump.setIdType(IdType.USER_HOME_PAGE.value());
        jump.putToMap("original", 2);//他人主页
        jump.putToMap("uid", jumpUid);

        // 操作
        Operation operation = new Operation();
        operation.setIdType(IdType.USER_HOME_PAGE.value());//用户主页
        operation.putToMap("original", 2);//他人主页
        operation.putToMap("uid", jumpUid);

        List<Option> options = new ArrayList<Option>();
        Option option1 = new Option();
        option1.setType(OperationType.AGREE.value());
        option1.setText("同意");
        Action action1 = new Action();
        action1.setActionUrl("/api/datesport/updateUserDatesportStatus");
        action1.putToMap("datesportId", datesportId+"");
        action1.putToMap("targetId", jumpUid+"");
        action1.putToMap("status", 3+"");
        option1.setAction(action1);

        Option option2 = new Option();
        option2.setType(OperationType.REFUSE.value());
        option2.setText("拒绝");
        Action action2 = new Action();
        action2.setActionUrl("/api/datesport/updateUserDatesportStatus");
        action2.putToMap("datesportId", datesportId+"");
        action2.putToMap("targetId", jumpUid+"");
        action2.putToMap("status", 4+"");
        option2.setAction(action2);

        options.add(option1);
        options.add(option2);
        operation.setOption(options);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.OPERATION_MSG.value());
        payload.setOperation(operation);
        payload.setJump(jump);
        payload.setNickname(nickname);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uid, lockTitle, boxTitle, payload);
    }

    @Override
    public boolean pushUserRefuseMessage(String title, int uid, String nickname, int jumpUid, String imgUrl) {
        String boxTitle = String.format("很抱歉，%s拒绝加入约运动“%s”。”。", nickname, title);
        String lockTitle = "约运动消息：" + boxTitle;

        // 跳转
        Jump jump = new Jump();
        jump.setIdType(IdType.USER_HOME_PAGE.value());
        jump.putToMap("original", 2);//他人主页
        jump.putToMap("uid", jumpUid);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setJump(jump);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uid, lockTitle, boxTitle, payload);
    }

    @Override
    public boolean pushCreatorRefuseMessage(String title, int uid, int datesportId, String imgUrl) {
        String boxTitle = String.format("很抱歉，您被拒绝加入约运动“%s”，不要灰心，继续探索吧。", title);
        String lockTitle = "约运动消息：" + boxTitle;

        Jump jump = new Jump();
        jump.setIdType(IdType.DATESPORT_DETAIL_PAGE.value());//约运动详情页
        jump.putToMap("datesportId", datesportId);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setJump(jump);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uid, lockTitle, boxTitle, payload);
    }

    @Override
    public boolean pushNoticeMessage(String title, List<Integer> uidList, int datesportId, String imgUrl) {
        if (uidList == null || uidList.size() <= 0) {
            return true;
        }
        String boxTitle = String.format("您参与的约运动“%s”，组织者发布了新的公告，快去查看吧!", title);
        String lockTitle = "约运动消息：" + boxTitle;

        Jump jump = new Jump();
        jump.setIdType(IdType.DATESPORT_DETAIL_PAGE.value());//约运动详情页
        jump.putToMap("datesportId", datesportId);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setJump(jump);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uidList, lockTitle, boxTitle, payload);
    }

    @Override
    public boolean pushCancelMessage(String title, List<Integer> uidList, int datesportId, String imgUrl) {
        String boxTitle = String.format("您参加的“%s”约运动已经取消了。", title);
        String lockTitle = "约运动消息：" + boxTitle;

        Jump jump = new Jump();
        jump.setIdType(IdType.DATESPORT_DETAIL_PAGE.value());//约运动详情页
        jump.putToMap("datesportId", datesportId);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setJump(jump);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uidList, lockTitle, boxTitle, payload);
    }

    @Override
    public boolean pushUserExitMessage(String title, int uid, int jonnedUid, String nickname, int datesportId, String imgUrl) {
        String boxTitle = String.format("“%s”退出了您创建的“%s”约运动。", nickname, title);
        String lockTitle = "约运动消息：" + boxTitle;

        // 跳转
        Jump jump = new Jump();
        jump.setIdType(IdType.USER_HOME_PAGE.value());
        jump.putToMap("original", 2);//他人主页
        jump.putToMap("uid", jonnedUid);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(BoxType.ABOUT_SPORTS_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setJump(jump);
        payload.setImg(imgUrl);

        return baseDatesportMessage(uid, lockTitle, boxTitle, payload);
    }

    private boolean baseDatesportMessage(List<Integer> uidList, String lockTitle, String boxTitle, Payload payload) {
        Alert alert = new Alert();
        alert.setTitle("百灵鸟");
        alert.setBody(lockTitle);

        PushMessage message = new PushMessage();
        message.setTag(BoxName.SPORTS.value() + "_" + System.currentTimeMillis());
        message.setAlert(alert);
        message.setTo(uidList);
        message.setLogo("lark_icon.png");
        message.setPayload(payload);

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        List<PushMessage> messages = new ArrayList<PushMessage>();
        messages.add(message);
        reqPushMessage.setMsgList(messages);

        String reqStr = GsonUtils.toJson(reqPushMessage);
        String responStr = HttpUtils.sendWebRequestByPostJsonStr(null, messagePushServiceUrl, reqStr, 30000);
        if (StringUtil.isBlankOrNull(responStr) || !StringUtil.isJsonStr(responStr)) {
            logger.info("约运动：调用C++消息推送服务返回为空或不为json字符串。请求：{}。晌应：{}。", reqStr, responStr);
            return false;
        }
        JSONObject jo = JSON.parseObject(responStr);
        boolean isSuccess = jo.getBoolean("ret");
        if (!isSuccess) {
            logger.info("约运动：调用消息推送服务异常。请求：{}。晌应：{}", reqStr, responStr);
        } else {
            logger.info("约运动：调用消息推送成功。请求：{}。晌应：{}", reqStr, responStr);
        }
        return isSuccess;
    }

    private boolean baseDatesportMessage(int uid, String lockTitle, String boxTitle, Payload payload) {
        List<Integer> toList = new ArrayList<Integer>();
        toList.add(uid);
        return baseDatesportMessage(toList, lockTitle, boxTitle, payload);
    }
}
